// page/serve/subscribe.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //普通选择器：（普通数组）
    store: [],
    project: [],
    projectId: '',
    index: 0, //默认显示位置
    current: 0,
    companyId: '',
    //日期
    timeList: [],
    //可预约天数
    yyDay: 30,
    //预约时间段
    hourList: [{
        hour: "8:00",
        n: 8,
        isShow: true
      },
      {
        hour: "9:00",
        n: 9,
        isShow: true
      },
      {
        hour: "10:00",
        n: 10,
        isShow: true
      },
      {
        hour: "11:00",
        n: 10,
        isShow: true
      },
      {
        hour: "12:00",
        n: 11,
        isShow: true
      },
      {
        hour: "13:00",
        n: 13,
        isShow: true
      },
      {
        hour: "14:00",
        n: 14,
        isShow: true
      },
      {
        hour: "15:00",
        n: 15,
        isShow: true
      },
      {
        hour: "16:00",
        n: 16,
        isShow: true
      },
      {
        hour: "17:00",
        n: 17,
        isShow: true
      },
      {
        hour: "18:00",
        n: 18,
        isShow: true
      },
      {
        hour: "19:00",
        n: 19,
        isShow: true
      }
    ],
    //是否显示
    timeShow: false,
    currentTab: 0,
    //选择时间
    chooseHour: "",
    //选择日期
    chooseTime: "",
    hourIndex: -1,
    //预约时间
    yyTime: '请选择预约时间 >'
  },
  //预约项目
  findrepairing: function() {
    var that = this
    app.getData({
      url: app.api.findrepairing(),
      method: 'POST',
      ok: function(res) {
        console.log(res)
        if (res.statusCode == 200 && res.errMsg == "request:ok") {
          if (res.data.code == 1) {
            that.setData({
              project: res.data.data
            })
          }
        }
      }
    })
  },
  //门店信息
  getStoreData: function() {
    var that = this
    app.getData({
      url: app.api.getStoreData(1, 32),
      method: 'POST',
      data: {
        latitude: app.globalData.locationInfo.latitude,
        longitude: app.globalData.locationInfo.longitude
      },
      ok: function(res) {
        console.log(res)
        if (res.statusCode == 200 && res.errMsg == "request:ok") {
          if (res.data.code == 1) {
            that.setData({
              store: res.data.data.list
            })
          }
        }
      }
    })
  },
  //弹出按钮
  showTimeModel: function() {
    this.setData({
      timeShow: !this.data.timeShow,
      chooseTime: this.data.timeList[0].date,
    });
  },
  //点击外部取消
  modelCancel: function() {
    this.setData({
      timeShow: !this.data.timeShow,
      chooseTime: this.data.timeList[0].date,
    });
  },
  //日期选择
  timeClick: function(e) {
    //非今天-不判断超过当前时间点(所有时间点都可选择)
    if (e.currentTarget.dataset.index != 0) {
      var list = this.data.hourList;
      for (var i = 0; i < list.length; i++) {
        list[i].isShow = true;
      }
      this.setData({
        hourList: list
      })
    } else {
      //今天-过时不可预约
      var hour = new Date().getHours();
      for (var i = 0; i < this.data.hourList.length; i++) {
        var list = this.data.hourList;
        if (this.data.hourList[i].n <= hour) {
          list[i].isShow = false;
          this.setData({
            hourList: list
          })
        }
      }
    }
    this.setData({
      currentTab: e.currentTarget.dataset.index,
      chooseTime: this.data.timeList[e.currentTarget.dataset.index].date,
      yyTime: '',
      chooseHour: "",
      hourIndex: -1
    });
    console.log(this.data.chooseTime)
  },
  // 时间选择
  hourClick: function(e) {
    var that = this;
    // 时间不可选择
    if (!e.currentTarget.dataset.isshow) {
      return false;
    }
    this.setData({
      hourIndex: e.currentTarget.dataset.index,
      chooseHour: this.data.hourList[e.currentTarget.dataset.index].hour,

    });
    var chooseTime = new Date().getFullYear() + "-" + this.data.chooseTime + " " + this.data.chooseHour
    this.setData({
      yyTime: chooseTime
    })
    console.log(chooseTime)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    Date.prototype.Format = function(format) {
      var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(), //day
        "h+": this.getHours(), //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
        "S": this.getMilliseconds() //millisecond
      }
      if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
      }
      for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
          format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
      }
      return format;
    }
    Date.prototype.DateAdd = function(interval, number) {
      number = parseInt(number);
      var date = new Date(this.getTime());
      switch (interval) {
        case "y":
          date.setFullYear(this.getFullYear() + number);
          break;
        case "m":
          date.setMonth(this.getMonth() + number);
          break;
        case "d":
          date.setDate(this.getDate() + number);
          break;
        case "w":
          date.setDate(this.getDate() + 7 * number);
          break;
        case "h":
          date.setHours(this.getHours() + number);
          break;
        case "n":
          date.setMinutes(this.getMinutes() + number);
          break;
        case "s":
          date.setSeconds(this.getSeconds() + number);
          break;
        case "l":
          date.setMilliseconds(this.getMilliseconds() + number);
          break;
      }
      return date;
    }



    var dateList = [];
    var now = new Date();
    for (var i = 0; i < this.data.yyDay; i++) {
      var d = {};
      var day = new Date().DateAdd('d', i).getDay();
      if (day == 1) {
        var w = "周一"
      }
      if (day == 2) {
        var w = "周二"
      }
      if (day == 3) {
        var w = "周三"
      }
      if (day == 4) {
        var w = "周四"
      }
      if (day == 5) {
        var w = "周五"
      }
      if (day == 6) {
        var w = "周六"
      }
      if (day == 0) {
        var w = "周日"
      }
      d.name = w;
      d.date = new Date().DateAdd('d', i).Format("MM-dd");
      dateList.push(d)
    }
    this.setData({
      timeList: dateList
    });
    //初始化判断
    //当前时间
    var hour = new Date().getHours();

    for (var i = 0; i < this.data.hourList.length; i++) {
      var list = this.data.hourList;
      //过时不可选
      if (this.data.hourList[i].n <= hour) {
        list[i].isShow = false;
        this.setData({
          hourList: list
        })
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.findrepairing()
    this.getStoreData()
  },
  bindPickerstore: function(e) {
    console.log(e)
    console.log(this.data.store[e.detail.value].companyId)
    var companyid = this.data.store[e.detail.value].companyId
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value,
      companyId: companyid
    })
  },
  bindPickerProject: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    console.log(this.data.project[e.detail.value].id)
    var projectid = this.data.project[e.detail.value].id
    console.log(e)
    this.setData({
      current: e.detail.value,
      projectId: projectid
    })
  },
  bindSave: function(e) {
    console.log(e)
    var that = this;
    // that.carInfo(e.detail.value, res.data.data.id);
    // console.log(that.data.isshow)
    var formData = e.detail.value;
    var myreg = /^(14[0-9]|13[0-9]|15[0-9]|17[0-9]|18[0-9])\d{8}$$/; //手机号
    var carCard = /(^(京[A-HJ-NPQY]|沪[A-HJ-N]|津[A-HJ-NPQR]|渝[A-DFGHN]|冀[A-HJRST]|晋[A-FHJ-M]|蒙[A-HJKLM]|辽[A-HJ-NP]|吉[A-HJK]|黑[A-HJ-NPR]|苏[A-HJ-N]|浙[A-HJKL]|皖[A-HJ-NP-S]|闽[A-HJK]|赣[A-HJKLMS]|鲁[A-HJ-NP-SUVWY]|豫[A-HJ-NP-SU]|鄂[A-HJ-NP-S]|湘[A-HJ-NSU]|粤[A-HJ-NP-Y]|桂[A-HJ-NPR]|琼[A-F]|川[A-HJ-MQ-Z]|贵[A-HJ]|云[AC-HJ-NP-SV]|藏[A-HJ]|陕[A-HJKV]|甘[A-HJ-NP]|青[A-H]|宁[A-E]|新[A-HJ-NP-S])([0-9A-HJ-NP-Z]{4}[0-9A-HJ-NP-Z挂试]|[0-9]{4}学|[A-D0-9][0-9]{3}警|[DF][0-9A-HJ-NP-Z][0-9]{4}|[0-9]{5}[DF])$|^WJ[京沪津渝冀晋蒙辽吉黑苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云藏陕甘青宁新]?[0-9]{4}[0-9JBXTHSD]$|^(V[A-GKMORTV]|K[A-HJ-NORUZ]|H[A-GLOR]|[BCGJLNS][A-DKMNORVY]|G[JS])[0-9]{5}$|^[0-9]{6}使$|^([沪粤川渝辽云桂鄂湘陕藏黑]A|闽D|鲁B|蒙[AEH])[0-9]{4}领$|^粤Z[0-9A-HJ-NP-Z][0-9]{3}[港澳]$)/; //车牌号
    var cjh = "^(\\d{17})$"
    // console.log(formData)
    if (that.data.projectId == null || that.data.projectId == ''){
      wx.showToast({
        title: '请选择预约项目',
        icon: 'none'
      })
    } else if (that.data.yyTime == null || that.data.yyTime == ''){
      wx.showToast({
        title: '请选择预约时间',
        icon: 'none'
      })
    } else if (that.data.companyId == null || that.data.companyId == ''){
      wx.showToast({
        title: '请选择预约门店',
        icon: 'none'
      })
    }else if (formData.userName == '') {
      wx.showToast({
        title: '用户名不能为空！',
        icon: 'none'
      })
    } else if (!(/^[\u4e00-\u9fa5]{2,4}$/.test(formData.userName))) {
      wx.showToast({
        title: '用户名不正确！',
        icon: 'none'
      })
    } else if (formData.mobile == '') {
      wx.showToast({
        title: '手机号不能为空！',
        icon: 'none'
      })
    } else if (!myreg.test(formData.mobile)) {
      wx.showToast({
        title: '请输入正确的手机号!',
        icon: 'none'
      })
    } else if (formData.carid == '') {
      wx.showToast({
        title: '车牌号不能为空！',
      })
    } else if (!(carCard.test(formData.carid))) {
      wx.showToast({
        title: '车牌号有误！',
      })
    } else if (formData.motorcycle == '') {
      wx.showToast({
        title: '车型不能为空！',
      })
    } else {
      app.getData({
        url: app.api.setRepairing(),
        method: 'POST',
        data: {
          type: that.data.projectId,
          appointment: that.data.yyTime+':00',
          storefront: that.data.companyId,
          member: formData.userName,
          phone: formData.mobile,
          carmodel: formData.motorcycle,
          number: formData.carid,
          content: formData.remark
        },
        ok:function(res){
          console.log(res)
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})